import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/api/api_client.dart';
import 'package:zywz/widgets/EmptyPlaceholder.dart';
import '../../bloc/service/service_bloc.dart';
import '../../generated/assets.dart';
import '../../models/services_data.dart';
import '../../widgets/financial_card.dart';
import '../../config/app_colors.dart';


class ServicesPage extends StatefulWidget {
  const ServicesPage({super.key});

  @override
  State<ServicesPage> createState() => _ServicesPageState();
}

class _ServicesPageState extends State<ServicesPage> with AutomaticKeepAliveClientMixin{
  @override
  bool get wantKeepAlive => true;


  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ServiceBloc>().add(ServiceEventInit());
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('章鱼问账'),
        backgroundColor: const Color(0xFFE3F2FD),
        elevation: 0,
        centerTitle: true,
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFE3F2FD), Colors.white],
            stops: [0.0, 0.3],
          ),
        ),
        child: BlocConsumer<ServiceBloc, ServiceState>(
          buildWhen: (previous, current) => current is ServiceSetSuccessState,
            listener: (context, state) {
              if(state is ServiceLoadingState){
                EasyLoading.show(status: '购买中');
                return;
              }else if(state is ServiceErrorState){
                EasyLoading.dismiss(animation: false);
                EasyLoading.showToast(state.message);
              }else if(state is ServiceBuySuccessState){
                EasyLoading.dismiss(animation: false);
                EasyLoading.showToast("WXPAY");
              }
            },
          builder: (context, state) {
            if(state is ServiceSetSuccessState){

              return  ListView(
              padding: const EdgeInsets.all(16),
              children: [
                // _buildHeaderCard(),
                GestureDetector(
                    onTap: (){
                      context.push('/preview?url=https://hongfund-app.oss-cn-hangzhou.aliyuncs.com/image/xuzhi.jpg&title=购买须知');
                    },
                    child: Image.asset(Assets.zywzAssetsRealGoumaixuzi)),
                const SizedBox(height: 20),
                Container(
                  padding: const EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.1),
                        spreadRadius: 2,
                        blurRadius: 8,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      ...(state?.data?.map((bean) =>
                          _buildServiceSection(bean?.serviceName ?? '', [
                            _buildServiceItem(
                              bean,
                              bean?.serviceName ?? '',
                              bean?.price?.toString() ?? '',
                              bean?.description ?? '',
                              bean?.detail ?? '',
                              bean?.unit ?? '',
                            )]),
                      ).toList()??[]),
                    ],
                  ),
                )





              ],
                              );
            }
            return const Center(
              child: EmptyPlaceholder(message: '暂无数据')
            );
          },
        ),
      ),
    );
  }

  Widget _buildHeaderCard() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        gradient: const LinearGradient(
          colors: [Color(0xFF29B6F6), Color(0xFF4DD0E1)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: const Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '结合大数据+AI智能分析',
            style: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 8),
          Text(
            '企业税务合规专家服务体系',
            style: TextStyle(color: Colors.white70, fontSize: 16),
          ),
        ],
      ),
    );
  }

  Widget _buildServiceSection(String title, List<Widget> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              width: 3,
              height: 15,
              color: AppColors.primaryColor,
              margin: const EdgeInsets.only(right: 8),
            ),
            Text(title, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold)),
            // TextButton(
            //   onPressed: () => GoRouter.of(context).push('/service-detail'),
            //   child: const Text('查看订单', style: TextStyle(color: Color(0xFF41C7DD))),
            // ),
          ],
        ),
        const SizedBox(height: 8),
        Divider(),
        const SizedBox(height: 8),
        ...items,
      ],
    );
  }

  Widget _buildServiceItem(ServicesBean bean,String title, String price, String description, String buttonText,String unit) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(child: Text(title,maxLines:1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500))),
            Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: price,
                      style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black,fontSize: 17),
                    ),
                    TextSpan(
                      text: unit,
                      style: TextStyle( color: Colors.black),
                    )
                  ],
                ),
              ),
            ),
            SizedBox(
              height: 26,
              child: ElevatedButton(
                onPressed: () {
                  final mapParam = LinkedHashMap<String, dynamic>();
                  mapParam['serviceId'] = bean?.serviceId;
                  mapParam['serviceName'] = bean?.serviceName;
                  mapParam['amount'] = bean?.price;
                  mapParam['tradeType'] = 'APP';

                  var bloc = context.read<ServiceBloc>();
                  bloc.add(ServiceOrderBuyEven(mapParam));
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4DD0E1),
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                  padding: const EdgeInsets.symmetric(horizontal: 11),
                ),
                child: Text('立即购买'),
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        Container(
          padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: const Color(0xFFE0F7FA),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Column(
              children: [
                Text(description, style: const TextStyle(color: Colors.black, height: 1.5)),
                if (buttonText.isNotEmpty)
                  GestureDetector(
                    onTap: (){
                      context.push('/services-detail',extra: bean);
                    },
                    child: Align(
                    alignment: Alignment.centerRight,
                    child: Text('查看详情', style: const TextStyle(color: Colors.blue),
                    ),
                                    ),
                  ),


              ],
            )),
        const SizedBox(height: 16),

      ],
    );
  }
}
